import React, {  useState } from 'react';
import { Form, message, AutoComplete, Upload, Button } from 'antd';
import ProForm, { ModalForm, ProFormText, ProFormDigit, ProFormRadio,ProFormUploadButton } from '@ant-design/pro-form';
import { getStudentSearchOptions, selectStudent } from '@/global/service';
import {
  saveThirdSgf
} from '../service'
import { baseUrl } from '@/utils/httpUrl';
interface AddFormProps {
  modalAddVisible: boolean;
  // uid: object;
  onCancel: () => void;
  onReload: () => void;
  courseId: number;
}

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const limitDecimals = (value: string | number): string => {
  const reg = /^(-)*(\d+)\.(\d).*$/;
  if(value > 300){
    return '300'
  }
  return `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',').replace(reg,'$1$2.$3');
};
const AddForm: React.FC<AddFormProps> = (props) => {
  const { modalAddVisible, onCancel, onReload , courseId} = props;
  const [form] = Form.useForm();
  const [sgf, setSgf] = useState<any>('');
  const [uid, setUid] = useState<string>()
  const [stepNum,setStepNum] = useState<number>(0)
  const [options, setOptions] = useState<{ value: string }[]>([]);
  const onSelect = (data: any, option: any) => {
    setUid(option.id);
  };
  const onSearch = async (keys: string) => {
    const data = await selectStudent({
      param :keys,
      courseId,
    });
    const options = getStudentSearchOptions(keys, data);
    setOptions(options);
  };
  const SgfUploadForm = {
    name: 'file',
    action: baseUrl.http + '/teacher-admin/admin/teacher/game/review/thirdSgf/upload',
    accept: '.sgf',
    headers: {
      'Authorization': `Bearer ${localStorage.getItem('auth-token')}`,
      'x-access-token': localStorage.getItem('token'),
    },
    maxCount: 1,
    // fileList:sgfFileList,
    onChange(info: { file: { status: string; name: any }; fileList: any }) {
      if (info.file.status !== 'uploading') {
        if (info.fileList.length === 0) {
          setSgf('');
        }
      }
      if (info.file.status === 'done') {
        if (info.file.response.code === 200) {
          const result = info.file.response.result;
          form.setFieldsValue({
            steps:`${result.steps}手`,
          })
          setStepNum(result.steps)
          setSgf(result.sgf)
          message.success(`${info.file.name}上传成功`);
        } else {
          message.error(info.file.response.message);
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name}上传失败`);
      }
    },
    beforeUpload: (file: any, fileList: any) => {
      console.log(fileList)
      if (sgf != '') {
        message.error('只能上传一个sgf');
        return Upload.LIST_IGNORE;
      }
      if (file.size > 1024 * 1024 * 10) {
        message.error('上传sgf文件大小超过10M');
        return Upload.LIST_IGNORE;
      }
      if (file.name.split('.').pop().toLowerCase() != 'sgf') {
        message.error('请上传sgf后缀的文件');
        return Upload.LIST_IGNORE;
      }
    },
  };
  const startReviewHandler = async (reviewId: any) => {

    if(window.electron){
      window.electron.ipcRenderer.openElectron({
        reviewId
      })
    } else {
      message.error('web端无法复盘')
    }

  }
  const onFinish = async function () {
    const values = form.getFieldsValue();
    form.validateFields()
    values.steps = stepNum
    saveThirdSgf({
      ...values,
      sgf,
      uid,
      courseId
    }).then(res=>{
      if(res.code === 200){
        message.success('保存成功')

        onReload();
        form.resetFields();
        setOptions([])
        setUid('');
        setSgf('')
        setStepNum(0)
        onCancel();
        startReviewHandler(res.result.id)

      } else {
        message.error(res.message)
      }
    })

  };
  const close = () => {
    form.resetFields();
    setOptions([])
    setUid('');
    setSgf('')
    setStepNum(0)
    onCancel();
  }
  return (
    <ModalForm
      title="添加三方复盘"
      visible={modalAddVisible}
      modalProps={{
        onCancel: close,
        destroyOnClose: true,
      }}
      form={form}
      {...formItemLayout}
      layout={'horizontal'}
      submitter={{
        render: () => [
          <Button key="1" onClick={close}>
            取消
          </Button>,
           <Button key="2" type="primary" onClick={onFinish}>
              开始复盘
          </Button>
        ],
      }}
    >
      <ProForm.Item
        name="uidName"
        label="选择用户"
        rules={[
          {
            required: true,
            message: '请输入昵称或手机号选择用户',
          },
        ]}
      >
        <AutoComplete
          options={options}
          onSelect={onSelect}
          onSearch={onSearch}
          placeholder="昵称/手机号"

        />
      </ProForm.Item>
     <ProFormRadio.Group
        name="userColor"
        label="用户执子"
        initialValue={1}
        fieldProps={{
          onChange:(e)=>{
            const type = e.target.value
              form.setFieldsValue({
                blackNickName: type === 1 ? '我' : '对手',
                whiteNickName: type === 2 ? '我' : '对手'
              })
            }
        }}
        options={[
          {
            label: '黑色',
            value: 1,
          },
          {
            label: '白色',
            value: 2,
          }
        ]}
      />
      <ProFormText
        label="执黑昵称"
        name="blackNickName"
        initialValue={'我'}
        fieldProps={{
          maxLength: 6,
        }}
        rules={[
          {
            required: true,
            message: '请输入执黑昵称',
          },
        ]}
      />
      <ProFormText
        label="执白昵称"
        name="whiteNickName"
        initialValue={'对手'}
        fieldProps={{
          maxLength: 6,
        }}
        rules={[
          {
            required: true,
            message: '请输入执白昵称',
          },
        ]}
      />
      <ProFormRadio.Group
        name="winner"
        label="获胜方"
        initialValue={1}
        options={[
          {
            label: '黑胜',
            value: 1,
          },
          {
            label: '白胜',
            value: 2,
          }
        ]}
      />
      <ProFormDigit
          label="获胜目数"
          name="winItems"
          min={0.5}
          max={300}
          fieldProps={{
            formatter: limitDecimals,
            parser: limitDecimals,
          }}
        />
        <ProFormUploadButton
            title="上传SGF文件"
            name="sgfUp"
            label="上传SGF"
            rules={[{ required: true, message: '请上传sgf文件' }]}
            fieldProps={{
              ...SgfUploadForm,
            }}
          />
        <ProFormText
          label="手数"
          name="steps"
          placeholder=" "
          disabled={true}
        />
    </ModalForm>
  );
};

export default AddForm;
